<?php
/**
 * 健康数据控制器
 * 处理健康记录、数据分析等
 */

class HealthController {
    private $db;
    
    public function __construct() {
        $database = Database::getInstance();
        $this->db = $database->getConnection();
    }
    
    /**
     * 记录健康数据
     */
    public function recordHealthData($data) {
        try {
            $userId = $this->getUserIdFromToken($data['token']);
            validateParams($data, ['bloodSugar', 'uricAcid', 'weight', 'recordDate']);
            
            // 检查是否已有当天的记录
            $stmt = $this->db->prepare("SELECT id FROM health_records WHERE user_id = ? AND record_date = ?");
            $stmt->execute([$userId, $data['recordDate']]);
            
            if ($stmt->fetch()) {
                // 更新记录
                $stmt = $this->db->prepare("UPDATE health_records SET blood_sugar = ?, uric_acid = ?, weight = ?, notes = ?, updated_at = NOW() WHERE user_id = ? AND record_date = ?");
                $stmt->execute([
                    $data['bloodSugar'],
                    $data['uricAcid'],
                    $data['weight'],
                    $data['notes'] ?? '',
                    $userId,
                    $data['recordDate']
                ]);
            } else {
                // 创建新记录
                $stmt = $this->db->prepare("INSERT INTO health_records (user_id, blood_sugar, uric_acid, weight, notes, record_date, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
                $stmt->execute([
                    $userId,
                    $data['bloodSugar'],
                    $data['uricAcid'],
                    $data['weight'],
                    $data['notes'] ?? '',
                    $data['recordDate']
                ]);
            }
            
            return apiSuccess(null, '健康数据记录成功');
            
        } catch (Exception $e) {
            return apiError($e->getMessage());
        }
    }
    
    /**
     * 获取健康历史记录
     */
    public function getHealthHistory($data) {
        try {
            $userId = $this->getUserIdFromToken($data['token']);
            $page = isset($data['page']) ? max(1, intval($data['page'])) : 1;
            $pageSize = isset($data['pageSize']) ? max(1, intval($data['pageSize'])) : 30;
            $offset = ($page - 1) * $pageSize;
            
            // 获取记录列表
            $stmt = $this->db->prepare("SELECT * FROM health_records WHERE user_id = ? ORDER BY record_date DESC LIMIT ? OFFSET ?");
            $stmt->execute([$userId, $pageSize, $offset]);
            $records = $stmt->fetchAll();
            
            // 获取总数
            $countStmt = $this->db->prepare("SELECT COUNT(*) as total FROM health_records WHERE user_id = ?");
            $countStmt->execute([$userId]);
            $total = $countStmt->fetch()['total'];
            
            $formattedRecords = array_map(function($record) {
                return [
                    'id' => $record['id'],
                    'bloodSugar' => $record['blood_sugar'],
                    'uricAcid' => $record['uric_acid'],
                    'weight' => $record['weight'],
                    'notes' => $record['notes'],
                    'recordDate' => $record['record_date'],
                    'createdAt' => $record['created_at']
                ];
            }, $records);
            
            return apiSuccess([
                'list' => $formattedRecords,
                'pagination' => [
                    'page' => $page,
                    'pageSize' => $pageSize,
                    'total' => $total,
                    'totalPages' => ceil($total / $pageSize)
                ]
            ]);
            
        } catch (Exception $e) {
            return apiError($e->getMessage());
        }
    }
    
    /**
     * 获取健康数据分析
     */
    public function getHealthAnalysis($data) {
        try {
            $userId = $this->getUserIdFromToken($data['token']);
            $days = isset($data['days']) ? intval($data['days']) : 30;
            
            // 获取最近N天的健康数据
            $startDate = date('Y-m-d', strtotime("-$days days"));
            
            $stmt = $this->db->prepare("SELECT * FROM health_records WHERE user_id = ? AND record_date >= ? ORDER BY record_date ASC");
            $stmt->execute([$userId, $startDate]);
            $records = $stmt->fetchAll();
            
            // 获取用户基本信息
            $userStmt = $this->db->prepare("SELECT h.* FROM user_health h WHERE h.user_id = ?");
            $userStmt->execute([$userId]);
            $userHealth = $userStmt->fetch();
            
            $analysis = $this->analyzeHealthData($records, $userHealth);
            
            return apiSuccess($analysis);
            
        } catch (Exception $e) {
            return apiError($e->getMessage());
        }
    }
    
    /**
     * 分析健康数据
     */
    private function analyzeHealthData($records, $userHealth) {
        if (empty($records)) {
            return [
                'message' => '暂无健康数据记录',
                'trends' => [],
                'recommendations' => []
            ];
        }
        
        // 计算趋势数据
        $bloodSugarData = [];
        $uricAcidData = [];
        $weightData = [];
        
        foreach ($records as $record) {
            $bloodSugarData[] = [
                'date' => $record['record_date'],
                'value' => $record['blood_sugar']
            ];
            $uricAcidData[] = [
                'date' => $record['record_date'],
                'value' => $record['uric_acid']
            ];
            $weightData[] = [
                'date' => $record['record_date'],
                'value' => $record['weight']
            ];
        }
        
        // 计算平均值
        $avgBloodSugar = array_sum(array_column($bloodSugarData, 'value')) / count($bloodSugarData);
        $avgUricAcid = array_sum(array_column($uricAcidData, 'value')) / count($uricAcidData);
        $avgWeight = array_sum(array_column($weightData, 'value')) / count($weightData);
        
        // 生成健康建议
        $recommendations = $this->generateRecommendations($avgBloodSugar, $avgUricAcid, $avgWeight, $userHealth);
        
        return [
            'trends' => [
                'bloodSugar' => $bloodSugarData,
                'uricAcid' => $uricAcidData,
                'weight' => $weightData
            ],
            'averages' => [
                'bloodSugar' => round($avgBloodSugar, 2),
                'uricAcid' => round($avgUricAcid, 2),
                'weight' => round($avgWeight, 2)
            ],
            'recommendations' => $recommendations
        ];
    }
    
    /**
     * 生成健康建议
     */
    private function generateRecommendations($bloodSugar, $uricAcid, $weight, $userHealth) {
        $recommendations = [];
        
        // 血糖建议
        if ($bloodSugar > 7.0) {
            $recommendations[] = [
                'type' => 'warning',
                'title' => '血糖偏高',
                'content' => '建议控制糖分摄入，增加膳食纤维，定期监测血糖',
                'priority' => 1
            ];
        } elseif ($bloodSugar > 6.1) {
            $recommendations[] = [
                'type' => 'info',
                'title' => '血糖临界',
                'content' => '血糖处于临界值，建议注意饮食控制',
                'priority' => 2
            ];
        } else {
            $recommendations[] = [
                'type' => 'success',
                'title' => '血糖正常',
                'content' => '血糖水平正常，继续保持健康饮食',
                'priority' => 3
            ];
        }
        
        // 尿酸建议
        if ($uricAcid > 420) {
            $recommendations[] = [
                'type' => 'warning',
                'title' => '尿酸偏高',
                'content' => '建议减少高嘌呤食物摄入，多喝水促进排泄',
                'priority' => 1
            ];
        } elseif ($uricAcid > 360) {
            $recommendations[] = [
                'type' => 'info',
                'title' => '尿酸临界',
                'content' => '尿酸值接近上限，建议注意饮食控制',
                'priority' => 2
            ];
        } else {
            $recommendations[] = [
                'type' => 'success',
                'title' => '尿酸正常',
                'content' => '尿酸水平正常，继续保持良好习惯',
                'priority' => 3
            ];
        }
        
        // 体重建议
        if ($userHealth && $userHealth['height']) {
            $bmi = $weight / (($userHealth['height'] / 100) * ($userHealth['height'] / 100));
            
            if ($bmi > 24) {
                $recommendations[] = [
                    'type' => 'warning',
                    'title' => '体重超重',
                    'content' => 'BMI指数偏高，建议控制热量摄入，增加运动',
                    'priority' => 1
                ];
            } elseif ($bmi < 18.5) {
                $recommendations[] = [
                    'type' => 'info',
                    'title' => '体重偏轻',
                    'content' => 'BMI指数偏低，建议适当增加营养摄入',
                    'priority' => 2
                ];
            } else {
                $recommendations[] = [
                    'type' => 'success',
                    'title' => '体重正常',
                    'content' => '体重在正常范围内，继续保持',
                    'priority' => 3
                ];
            }
        }
        
        // 按优先级排序
        usort($recommendations, function($a, $b) {
            return $a['priority'] - $b['priority'];
        });
        
        return $recommendations;
    }
    
    /**
     * 从token中获取用户ID
     */
    private function getUserIdFromToken($token) {
        $parts = explode('.', $token);
        if (count($parts) !== 3) {
            throw new Exception('Token格式错误');
        }
        
        $payload = json_decode(base64_decode($parts[1]), true);
        return $payload['user_id'];
    }
}

?>